package m4;

import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.Scanner;

public class Consumer {
    public static void main(String[] args) throws Exception {
        // 连接消息服务器
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");   // wht6.cn
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        // 1.定义随机队列  2.定义交换机  3.绑定，指定绑定键
        // 由服务器自动随机命名, 非持久,独占,自动删除
        String queue = c.queueDeclare().getQueue();
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);

        System.out.println("输入绑定键， 用空格隔开：");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");  // ["aaa", "bbb", "ccc"]
        for (String key:a) {
            c.queueBind(queue, "direct_logs", key);
        }


        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                String key = message.getEnvelope().getRoutingKey();
                System.out.println(key + " - " + msg);
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        c.basicConsume(queue, true, deliverCallback, cancelCallback);
    }
}
